package com.study.experiment04.servlet;

import com.study.experiment04.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author WS
 */
@WebServlet(name = "ServletSession", urlPatterns = "/experiment04/ServletSession")
public class ServletSession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(username, password);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = dateFormat.format(new Date());
        //new 一个session来保存user、dateTime对象
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        session.setAttribute("loginTime", dateTime);
        session.setAttribute("sessionId", session.getId());
        //请求转发
        request.getRequestDispatcher("index1.jsp").forward(request, response);
    }
}
